/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package imageuploaddb;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

/**
 *
 * @author Homeroe
 */
public class main extends javax.swing.JFrame {
// Globals

static String report = "";
static Connection con;
static ResultSet rs;
    /**
     * Creates new form main
     */
    public main() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        dirPath = new javax.swing.JTextField();
        textRoot = new javax.swing.JLabel();
        uploadButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        textReport = new javax.swing.JTextArea();
        makeRelation = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        dirPath.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dirPathActionPerformed(evt);
            }
        });

        textRoot.setText("Root:");

        uploadButton.setText("Subir");
        uploadButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                uploadButtonActionPerformed(evt);
            }
        });

        textReport.setEditable(false);
        textReport.setColumns(20);
        textReport.setRows(5);
        jScrollPane1.setViewportView(textReport);

        makeRelation.setText("Hacer relacion");
        makeRelation.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                makeRelationActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(makeRelation))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(textRoot)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(dirPath, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(uploadButton)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dirPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textRoot)
                    .addComponent(uploadButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(makeRelation)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void dirPathActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dirPathActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_dirPathActionPerformed

    private Image ConvertirImagen(byte[] bytes,String ext) throws IOException {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        Iterator readers = ImageIO.getImageReadersByFormatName(ext);
        ImageReader reader = (ImageReader) readers.next();
        Object source = bis; // File or InputStream
        ImageInputStream iis = ImageIO.createImageInputStream(source);
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
        return reader.read(0, param);
    } 
    
    private void uploadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uploadButtonActionPerformed
        if(!dirPath.getText().isEmpty()){
            File[] files = new File(dirPath.getText()).listFiles();
            try {
                con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/teslaPrueba?"+"user=root&password=nugget-1");
                showFiles(files,"root",-1);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            } catch (    IOException | SQLException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            textReport.setText("Escribe una direccion primero");
        }
    }//GEN-LAST:event_uploadButtonActionPerformed

    private void makeRelationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_makeRelationActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_makeRelationActionPerformed

    public boolean isInteger(String str) {
        try {
            Integer.parseInt(str);
            return true;
        } catch (NumberFormatException nfe) {}
        return false;
    }
    
    public void showFiles(File[] files,String parentDir,int sub) throws SQLException, FileNotFoundException, IOException {
        InputStream fis;
        PreparedStatement st;
        String ext = "";
        String query = "";
        int archid = -1;
        sub+=1;
        for (File file : files) {
            if (file.isDirectory()) {
                // Añade guiones por cada nivel de directorio
                for(int i=0;i<sub;i++){report+="-";}
                report += "Directorio: " + file.getName()+"\n";
                // Recursión para revisar todas las carpeta/archivos
                showFiles(file.listFiles(),file.getName(),sub);
            } else {
                // Añade guiones por cada nivel de directorio
                for(int i=0;i<sub;i++){report+="-";}
                report += "Archivo: " + file.getName();
                ext = file.getName().split("\\.")[1];
                // Si tiene extencion de imagen y esta muy grande, la hace mas pequeña. Si no, sube el archivo tal cual
                if(ext.contentEquals("jpg")||ext.contentEquals("gif")||ext.contentEquals("png")){
                    BufferedImage img = ImageIO.read(file);
                    Image res;
                    if(img.getWidth()>600){
                        res = img.getScaledInstance(150, 150, 10);
                        ByteArrayOutputStream os = new ByteArrayOutputStream();
                        ImageIO.write(img,ext, os);
                        fis = new ByteArrayInputStream(os.toByteArray());                   
                    } else  fis = new FileInputStream(file);
                } else  fis = new FileInputStream(file);
                // Checamos si ya hay un archivo igual
                st = (PreparedStatement)con.prepareStatement("SELECT id,nombre,ext FROM archivos WHERE nombre=? AND ext=? LIMIT 1");
                st.setString(1,file.getName());
                st.setString(2,ext);
                rs = st.executeQuery();
                // Si el archivo NO existe, lo mete a la base de datos
                if(!rs.next()){
                    report += "[Nuevo archivo]";
                    st = (PreparedStatement)con.prepareStatement("INSERT INTO archivos(nombre,ext,archivo,dir) VALUES(?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
                    st.setString(1,file.getName());
                    st.setString(2,ext);
                    st.setBinaryStream(3, fis, (int) file.length());
                    st.setString(4,file.getCanonicalPath());
                    st.executeUpdate();
                    rs = st.getGeneratedKeys();
                    rs.next();
                } else {
                    // Ya hay un archivo con ese nombre, probamos si es el mismo archivo por bytes. (Esto para
                    // reducir la carga en consultas)
                    st = (PreparedStatement)con.prepareStatement("SELECT id,nombre,ext,blob FROM archivos WHERE nombre=? AND ext=? LIMIT 1");
                    st.setString(1,file.getName());
                    st.setString(2,ext);
                    rs = st.executeQuery();
                    if(rs.getBlob(4)==fis){
                        report += "[Archivo repetido]";
                    } else{
                        report += "[Nuevo archivo]";
                        st = (PreparedStatement)con.prepareStatement("INSERT INTO archivos(nombre,ext,archivo,dir) VALUES(?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
                        st.setString(1,file.getName());
                        st.setString(2,ext);
                        st.setBinaryStream(3, fis, (int) file.length());
                        st.setString(4,file.getCanonicalPath());
                        st.executeUpdate();
                        rs = st.getGeneratedKeys();
                        rs.next();
                    }
                }
                archid = rs.getInt(1);
                // Si el checkbox de relacion esta TRUE, relaciona el archivo con el numero/nombre de la carpeta padre
                if (makeRelation.isSelected() && isInteger(parentDir)){
                    report += "[Relacion creada]";
                    st = (PreparedStatement)con.prepareStatement("INSERT INTO archivo_relacion(archivoId,productoId) VALUES(?,?)");
                    st.setInt(1,archid);
                    st.setInt(2,Integer.parseInt(parentDir));
                    st.execute();
                }
                report += "\n";
            }
        }
        textReport.setText(""+report+"");
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new main().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField dirPath;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JCheckBox makeRelation;
    private javax.swing.JTextArea textReport;
    private javax.swing.JLabel textRoot;
    private javax.swing.JButton uploadButton;
    // End of variables declaration//GEN-END:variables
}
